//
//  HighScoresLayer.m
//  xGame
//
//  Created by Max on 11-8-13.
//  Copyright 2011年 __MyCompanyName__. All rights reserved.
//

#import "HighScoresLayer.h"
#import "BaseLayer.h"
#import "GameLayer.h"

@interface HighScoresLayer (Private)
- (void)loadCurrentPlayer;
- (void)loadHighscores;
- (void)updateHighscores;
- (void)saveCurrentPlayer;
- (void)saveHighscores;
- (void)button1Callback:(id)sender;
- (void)button2Callback:(id)sender;
@end


@implementation HighScoresLayer
@synthesize currentScore;
@synthesize gameLayer = _gameLayer;

+(CCScene *) scene
{
    // 'scene' is an autorelease object.
	CCScene *scene = [CCScene node];
	
	// 'layer' is an autorelease object.
	HighScoresLayer *layer = [HighScoresLayer node];
	
	// add layer as a child to scene
	[scene addChild: layer];
	
	// return the scene
	return scene;
    
}

- (id)init {
    //	NSLog(@"Highscores::init");
	
	if(![super init]) return nil;
    
    //	NSLog(@"lastScore = %d",lastScore);
	
	currentScore = g_lastScore;
    
    //	NSLog(@"currentScore = %d",currentScore);
	
	[self loadCurrentPlayer];
	[self loadHighscores];
	[self updateHighscores];
	if(currentScorePosition >= 0) {
		[self saveHighscores];
	}
	
    CCSpriteBatchNode *spriteManager = (CCSpriteBatchNode*)[self getChildByTag:kSpriteManager];
    
    CCSprite *title = [CCSprite spriteWithBatchNode:spriteManager rect:CGRectMake(608,192,225,57)];
	[spriteManager addChild:title z:5];
	title.position = ccp(160,420);
    
	float start_y = 360.0f;
	float step = 27.0f;
	int count = 0;
	for(NSMutableArray *highscore in highscores) {
		NSString *player = [highscore objectAtIndex:0];
		int score = [[highscore objectAtIndex:1] intValue];
        
        CCLabelBMFont *label1 = [CCLabelBMFont labelWithString:[NSString stringWithFormat:@"%d",(count+1)] fntFile:@"bitmapFont.fnt"];
        [label1 setColor:ccc3(0, 0, 0)];
        [label1 setOpacity:200];
        [label1 setScale:0.6];
        [self addChild:label1 z:5];
        label1.position = ccp(20,start_y-count*step-2.0f);
		
        NSLog(@"player=%@",player);
        CCLabelBMFont *label2 =[CCLabelBMFont labelWithString:player fntFile:@"font09.fnt"];
        [label2 setColor:ccc3(0, 0, 0)];
        [label2 setOpacity:200];
        [label2 setScale:0.6];
        [self addChild:label2 z:5];
        label2.position = ccp(100,start_y-count*step-2.0f);
        
        CCLabelBMFont *label3 =[CCLabelBMFont labelWithString:[NSString stringWithFormat:@"%d",score] fntFile:@"bitmapFont.fnt"];
        //		[label3 setColor:ccc3(0, 0, 0)];
        [label3 setOpacity:200];
        [label3 setScale:0.6];
        [self addChild:label3 z:5];
        label3.position = ccp(240, start_y-count*step);
        
		count++;
		if(count == 10) break;
	}
    
    CCMenuItemImage *button1 = [CCMenuItemImage itemFromNormalImage:@"playAgainButton.png" selectedImage:@"playAgainButton.png" target:self selector:@selector(button1Callback:)];
	CCMenuItemImage *button2 = [CCMenuItemImage itemFromNormalImage:@"changePlayerButton.png" selectedImage:@"changePlayerButton.png" target:self selector:@selector(button2Callback:)];
	
	CCMenu *menu = [CCMenu menuWithItems: button1, button2, nil];
    
	[menu alignItemsVerticallyWithPadding:9];
	menu.position = ccp(160,58);
    
	
	[self addChild:menu];
	
	return self;
}

- (id)initWithScore:(int)lastScore {
    //	NSLog(@"Highscores::init");
	
	if(![super init]) return nil;
    
    //	NSLog(@"lastScore = %d",lastScore);
	
	currentScore = lastScore;
    
    //	NSLog(@"currentScore = %d",currentScore);
	
	[self loadCurrentPlayer];
	[self loadHighscores];
	[self updateHighscores];
	if(currentScorePosition >= 0) {
		[self saveHighscores];
	}
	
    //	AtlasSpriteManager *spriteManager = (AtlasSpriteManager*)[self getChildByTag:kSpriteManager];
    CCSpriteBatchNode *spriteManager = (CCSpriteBatchNode*)[self getChildByTag:kSpriteManager];
    
    //	AtlasSprite *title = [AtlasSprite spriteWithRect:CGRectMake(608,192,225,57) spriteManager:spriteManager];
    CCSprite *title = [CCSprite spriteWithBatchNode:spriteManager rect:CGRectMake(608,192,225,57)];
	[spriteManager addChild:title z:5];
	title.position = ccp(160,420);
    
	float start_y = 360.0f;
	float step = 27.0f;
	int count = 0;
	for(NSMutableArray *highscore in highscores) {
		NSString *player = [highscore objectAtIndex:0];
		int score = [[highscore objectAtIndex:1] intValue];
        
        CCLabelAtlas *label1 = [CCLabelAtlas labelWithString:[NSString stringWithFormat:@"%d",(count+1)] charMapFile:@"fps_images.png" itemWidth:30 itemHeight:40 startCharMap:'.'];
		[self addChild:label1 z:5];
		[label1 setOpacity:200];
		label1.position = ccp(15,start_y-count*step-2.0f);
            
        CCLabelAtlas *label2 = [CCLabelAtlas labelWithString:player charMapFile:@"fps_images.png" itemWidth:240 itemHeight:40 startCharMap:'.'];
		[self addChild:label2 z:5];
        //		[label2 setRGB:0 :0 :0];
		label2.position = ccp(160,start_y-count*step);
        
        CCLabelAtlas *label3 = [CCLabelAtlas labelWithString:[NSString stringWithFormat:@"%d",score] charMapFile:@"fps_images.png" itemWidth:290 itemHeight:40 startCharMap:'.'];
		[self addChild:label3 z:5];
        //		[label3 setRGB:0 :0 :0];
		[label3 setOpacity:200];
		label3.position = ccp(160,start_y-count*step);
		
		count++;
		if(count == 10) break;
	}
    
    CCMenuItemImage *button1 = [CCMenuItemImage itemFromNormalImage:@"playAgainButton.png" selectedImage:@"playAgainButton.png" target:self selector:@selector(button1Callback:)];
	CCMenuItemImage *button2 = [CCMenuItemImage itemFromNormalImage:@"changePlayerButton.png" selectedImage:@"changePlayerButton.png" target:self selector:@selector(button2Callback:)];
	
	CCMenu *menu = [CCMenu menuWithItems: button1, button2, nil];
    
	[menu alignItemsVerticallyWithPadding:9];
	menu.position = ccp(160,58);
    
	
	[self addChild:menu];
	
	return self;
}

- (void)dealloc {
    //	NSLog(@"Highscores::dealloc");
	[highscores release];
	[super dealloc];
}

- (void)loadCurrentPlayer {
    //	NSLog(@"loadCurrentPlayer");
	
	NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
	
	currentPlayer = nil;
	currentPlayer = [defaults objectForKey:@"player"];
	if(!currentPlayer) {
		currentPlayer = @"anonymous";
	}
    //	NSLog(@"currentPlayer = %@",currentPlayer);
}

- (void)loadHighscores {
    //	NSLog(@"loadHighscores");
	
	NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
	
	highscores = nil;
	highscores = [[NSMutableArray alloc] initWithArray: [defaults objectForKey:@"highscores"]];
#ifdef RESET_DEFAULTS	
	[highscores removeAllObjects];
#endif
	if([highscores count] == 0) {
		[highscores addObject:[NSArray arrayWithObjects:@"tweejump",[NSNumber numberWithInt:1000000],nil]];
		[highscores addObject:[NSArray arrayWithObjects:@"tweejump",[NSNumber numberWithInt:750000],nil]];
		[highscores addObject:[NSArray arrayWithObjects:@"tweejump",[NSNumber numberWithInt:500000],nil]];
		[highscores addObject:[NSArray arrayWithObjects:@"tweejump",[NSNumber numberWithInt:250000],nil]];
		[highscores addObject:[NSArray arrayWithObjects:@"tweejump",[NSNumber numberWithInt:100000],nil]];
		[highscores addObject:[NSArray arrayWithObjects:@"tweejump",[NSNumber numberWithInt:50000],nil]];
		[highscores addObject:[NSArray arrayWithObjects:@"tweejump",[NSNumber numberWithInt:20000],nil]];
		[highscores addObject:[NSArray arrayWithObjects:@"tweejump",[NSNumber numberWithInt:10000],nil]];
		[highscores addObject:[NSArray arrayWithObjects:@"tweejump",[NSNumber numberWithInt:5000],nil]];
		[highscores addObject:[NSArray arrayWithObjects:@"tweejump",[NSNumber numberWithInt:1000],nil]];
	}
#ifdef RESET_DEFAULTS	
	[self saveHighscores];
#endif
}

- (void)updateHighscores {
    //	NSLog(@"updateHighscores");
	
	currentScorePosition = -1;
	int count = 0;
	for(NSMutableArray *highscore in highscores) {
		int score = [[highscore objectAtIndex:1] intValue];
		
		if(currentScore >= score) {
			currentScorePosition = count;
			break;
		}
		count++;
	}
	
	if(currentScorePosition >= 0) {
		[highscores insertObject:[NSArray arrayWithObjects:currentPlayer,[NSNumber numberWithInt:currentScore],nil] atIndex:currentScorePosition];
		[highscores removeLastObject];
	}
}

- (void)saveCurrentPlayer {
    //	NSLog(@"saveCurrentPlayer");
    //	NSLog(@"currentPlayer = %@",currentPlayer);
	
	NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
	
	[defaults setObject:currentPlayer forKey:@"player"];
}

- (void)saveHighscores {
    //	NSLog(@"saveHighscores");
	
	NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
	
	[defaults setObject:highscores forKey:@"highscores"];
}

- (void)button1Callback:(id)sender {
    //	NSLog(@"button1Callback");
    
    //	Scene *scene = [[Scene node] addChild:[Game node] z:0];
    //	TransitionScene *ts = [FadeTransition transitionWithDuration:0.5f scene:scene withColorRGB:0xffffff];
    //	[[Director sharedDirector] replaceScene:ts];
    
    //    CCScene *scene = [CCScene node];
    //    [scene addChild:[Game node] z:0];
    //	CCTransitionScene *ts = [CCTransitionScene transitionWithDuration:0.5f scene:scene];
    
    CCTransitionScene *ts =[CCTransitionScene transitionWithDuration:0.5f scene:[GameLayer scene]];
	[[CCDirector sharedDirector] replaceScene:ts];
}

- (void)button2Callback:(id)sender {
    //	NSLog(@"button2Callback");
	
	changePlayerAlert = [UIAlertView new];
	changePlayerAlert.title = @"Change Player";
	changePlayerAlert.message = @"\n";
	changePlayerAlert.delegate = self;
	[changePlayerAlert addButtonWithTitle:@"Save"];
	[changePlayerAlert addButtonWithTitle:@"Cancel"];
    
	changePlayerTextField = [[UITextField alloc] initWithFrame:CGRectMake(20, 45, 245, 27)];
	changePlayerTextField.borderStyle = UITextBorderStyleRoundedRect;
	[changePlayerAlert addSubview:changePlayerTextField];
    //	changePlayerTextField.placeholder = @"Enter your name";
    //	changePlayerTextField.clearButtonMode = UITextFieldViewModeWhileEditing;
	changePlayerTextField.keyboardType = UIKeyboardTypeDefault;
	changePlayerTextField.returnKeyType = UIReturnKeyDone;
	changePlayerTextField.autocorrectionType = UITextAutocorrectionTypeNo;
	changePlayerTextField.autocapitalizationType = UITextAutocapitalizationTypeNone;
	changePlayerTextField.delegate = self;
	[changePlayerTextField becomeFirstResponder];
    
	[changePlayerAlert show];
}

- (void)draw {
    //	NSLog(@"draw");
    
	if(currentScorePosition < 0) return;
	
	glColor4ub(0,0,0,50);
    
	float w = 320.0f;
	float h = 27.0f;
	float x = (320.0f - w)/2;
	float y = 359.0f - currentScorePosition * h;
    
	GLfloat vertices[4][2];	
	GLubyte indices[4] = { 0, 1, 3, 2 };
	
	glVertexPointer(2, GL_FLOAT, 0, vertices);
	glEnableClientState(GL_VERTEX_ARRAY);
	
	vertices[0][0] = x;		vertices[0][1] = y;
	vertices[1][0] = x+w;	vertices[1][1] = y;
	vertices[2][0] = x+w;	vertices[2][1] = y+h;
	vertices[3][0] = x;		vertices[3][1] = y+h;
	
	glDrawElements(GL_TRIANGLE_STRIP, 4, GL_UNSIGNED_BYTE, indices);
	
	glDisableClientState(GL_VERTEX_ARRAY);	
}

- (void)changePlayerDone {
	currentPlayer = [changePlayerTextField.text retain];
	[self saveCurrentPlayer];
	if(currentScorePosition >= 0) {
		[highscores removeObjectAtIndex:currentScorePosition];
		[highscores addObject:[NSArray arrayWithObjects:@"tweejump",[NSNumber numberWithInt:0],nil]];
		[self saveHighscores];
        //		Highscores *h = [[Highscores alloc] initWithScore:currentScore];
        //		Scene *scene = [[Scene node] addChild:h z:0];
        //		[[Director sharedDirector] replaceScene:[FadeTransition transitionWithDuration:1 scene:scene withColorRGB:0xffffff]];
        HighScoresLayer *h = [[HighScoresLayer alloc] initWithScore:currentScore];
		CCScene *scene = [CCScene node];
        [scene addChild:h z:0];
		[[CCDirector sharedDirector] replaceScene:[CCTransitionFade transitionWithDuration:1 scene:scene withColor:ccWHITE]];
	}
}

- (void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex {
    //	NSLog(@"alertView:clickedButtonAtIndex: %i",buttonIndex);
	
	if(buttonIndex == 0) {
		[self changePlayerDone];
	} else {
		// nothing
	}
}

- (BOOL)textFieldShouldReturn:(UITextField *)textField {
    //	NSLog(@"textFieldShouldReturn");
	[changePlayerAlert dismissWithClickedButtonIndex:0 animated:YES];
	[self changePlayerDone];
	return YES;
}

@end
